package com.kim.weixinProject.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import com.dms.ezplatform.weixin.RemoteInvoke;
import com.dms.ezplatform.weixin.ResourceConfiguration;
import com.dms.ezplatform.weixin.WeiXinContents;
import com.dms.ezplatform.weixin.WeixinInvokeException;
import com.dms.ezplatform.weixin.authentication.WeixinAuthenticateException;
import com.dms.ezplatform.weixin.message.MessageSendInfo;
import com.dms.ezplatform.weixin.message.MessageSendResult;
import com.kim.weixinProject.token.dao.AccessTokenDao;
import com.kim.weixinProject.token.model.AccessTokenModel;

import net.sf.json.JSONObject;

public class WxUtils {

    private static ResourceConfiguration configuration;
	
	public void setConfiguration(ResourceConfiguration configuration) {
		WxUtils.configuration = configuration;
	}
	
	private static AccessTokenDao queryService(){
		return SpringUtils.getBean(AccessTokenDao.class);
	}
	
	private static String accessToken = "";
	
	public static String getAccessToken() throws ParseException {
		List<AccessTokenModel> list = queryService().findAll();
		if(list != null && !list.isEmpty()) {
			AccessTokenModel model = list.get(0);
			int expires_in = model.getExpiresin();
			long create_time = model.getCreatetime();
            if ((System.currentTimeMillis()-create_time)/1000 < expires_in) {// 有效  
                System.out.println("无须创建");  
                accessToken = model.getAccesstoken();
            } else {// 无效  
                System.out.println("创建Access_Token");  
                //当前日期
            	accessToken = RemoteInvoke.getAccessToken();
            	model.setAccesstoken(accessToken);
            	model.setExpiresin(7000);
            	model.setTs(System.currentTimeMillis());
            	model.setCreatetime(System.currentTimeMillis());//
            	model.setUpdatetime(System.currentTimeMillis());//更新时间
            	queryService().save(model);
            }
		} else {
			AccessTokenModel model = new AccessTokenModel();
			accessToken = RemoteInvoke.getAccessToken();
			model.setAccesstoken(accessToken);
			model.setExpiresin(7000);
			model.setTs(System.currentTimeMillis());
        	model.setCreatetime(System.currentTimeMillis());//
        	model.setUpdatetime(System.currentTimeMillis());//更新时间
        	queryService().save(model);
		}
		
		return accessToken;
	}
	
	/**
	 * 微信登录验证Oauth
	 * @param code
	 * @return
	 */
	public static String OauthValid(String code) {
		try {
			configuration = new ResourceConfiguration();
			configuration.initial();
			String uri = configuration.getConfigValue(WeiXinContents.WEIXIN_QY_OAUTH_GETUSERCODE+2, getAccessToken(), code);
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(uri);
			HttpResponse response = httpClient.execute(httpGet);
			if(HttpStatus.SC_OK != response.getStatusLine().getStatusCode()){
				throw new WeixinInvokeException("请求失败: " + response.getStatusLine().getReasonPhrase());
			}
			HttpEntity responseEntity = response.getEntity();
			JSONObject json = JSONObject.fromObject(EntityUtils.toString(responseEntity));
			if(json.containsKey(WeiXinContents.RESPONSE_KEY_ERRCODE)){
				String errorCode = json.getString(WeiXinContents.RESPONSE_KEY_ERRCODE);
				String errorMessage = json.getString(WeiXinContents.RESPONSE_KEY_ERRMSG);
				if(json.getInt(WeiXinContents.RESPONSE_KEY_ERRCODE) != 0){
					System.out.println(errorCode+"==========="+errorMessage);
				}else{
					throw new WeixinAuthenticateException(String.format("[ errorcode: %s ] - %s", errorCode, errorMessage));
				}
				//throw new WeixinAuthenticateException(String.format("[ errorcode: %s ] - %s", errorCode, errorMessage));
			}
			if(json.has("UserId")){
				return json.getString("UserId");
			}
			throw new WeixinInvokeException("未知错误");
		} catch (Exception e) {
			throw new WeixinInvokeException(e);
		}
	}
	
	public static MessageSendResult sendMessage(MessageSendInfo info) {
		try {
			configuration = new ResourceConfiguration();
			configuration.initial();
			String uri = configuration.getConfigValue(WeiXinContents.WEIXIN_QY_MESSAGE_SEND, getAccessToken());
			@SuppressWarnings({ "resource", "deprecation" })
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(uri);
			JSONObject requestJson = info.toJSONString();
			StringEntity requestEntity = new StringEntity(requestJson.toString(), HTTP.UTF_8);
			post.setEntity(requestEntity);
			HttpResponse response = httpClient.execute(post);
			if(HttpStatus.SC_OK != response.getStatusLine().getStatusCode()){
				throw new WeixinInvokeException("请求失败: " + response.getStatusLine().getReasonPhrase());
			}
			HttpEntity responseEntity = response.getEntity();
			if(responseEntity != null){
				JSONObject json = JSONObject.fromObject(EntityUtils.toString(responseEntity));
				if(json.getInt(WeiXinContents.RESPONSE_KEY_ERRCODE) != 0){
					String errorCode = json.getString(WeiXinContents.RESPONSE_KEY_ERRCODE);
					String errorMessage = json.getString(WeiXinContents.RESPONSE_KEY_ERRMSG);
					System.out.println(String.format("[ errorcode: %s ] - %s", errorCode, errorMessage));
					//throw new WeixinMessageException(String.format("[ errorcode: %s ] - %s", errorCode, errorMessage));
				}
				return (MessageSendResult) JSONObject.toBean(json, MessageSendResult.class);
			}else{
				throw new NullPointerException("remote invoke timeout.");
			}
		} catch (Exception e) {
			throw new WeixinInvokeException(e);
		}
	}
	
	public static Date getTime (String time) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
		return sdf.parse(time);
	}
}
